package com.novunda.platform.services;

import com.novunda.platform.common.handler.LogCallBack;
import com.novunda.platform.common.utils.UserUtils;
import com.novunda.platform.common.web.modal.Page;
import com.novunda.platform.entities.EmailInfo;
import com.novunda.platform.entities.Log;
import com.novunda.platform.entities.User;
import com.novunda.platform.repositories.EmailRepository;
import com.novunda.platform.repositories.UserRepository;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

/**
 * 邮件服务操作接口
 * Created by YJY on 2016/9/12.
 */
@Transactional
@Service
public class EmailService extends BaseService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private EmailRepository emailRepository;

    /**
     * 邮件服务器查询分页
     *
     * @param page 页面信息
     * @return 分页数据
     */
    public Page<EmailInfo> findEmailInfo(Page<EmailInfo> page) {
        DetachedCriteria dc = emailRepository.createDetachedCriteria();
        User currentUser = UserUtils.getUser();
        if (!currentUser.isAdmin()) {
            dc.createAlias("office", "office");
            dc.add(dataScopeFilter(currentUser, "office", ""));
        }
        dc.addOrder(Order.desc("id"));
//        // 如果不是超级管理员，则不显示超级管理员用户
//        if (!currentUser.isAdmin()) {
//            dc.add(Restrictions.ne("id", 1L));
//            if (StringUtils.isNotEmpty(currentUser.getCompany().getName())) {
//                dc.add(Restrictions.eq("organization", currentUser.getCompany().getName()));
//            }
//        }
        return emailRepository.find(page, dc);
    }

    /**
     * 根据id查询邮件信息
     *
     * @param id 邮件服务器id
     * @return 邮件服务器信息
     */
    public EmailInfo get(Long id) {
        return emailRepository.get(id);
    }

    /**
     * 创建邮件服务器信息
     *
     * @param emailInfo 邮件服务器信息
     */
    public EmailInfo createEmail(final EmailInfo emailInfo) {
        handler.doHandler(new LogCallBack() {
            @Override
            public Object doHandler() {
                emailRepository.save(emailInfo);
                return null;
            }

            @Override
            public Log generate() {
                Log log = new Log();
                log.setType("新增");
                log.setName("新增邮件服务器");
                log.setDescription("新增邮件服务器");
                return log;
            }

            @Override
            public boolean forceLog() {
                return false;
            }
        });
        return emailInfo;
    }

    /**
     * 修改默认邮件
     *
     * @param id 邮件服务器id
     */
    public EmailInfo updateDefaultEmail(Long id) {
        EmailInfo emailInfo = get(id);
        return setEmailState(emailInfo);
    }

    /**
     * 设置默认邮件服务器
     *
     * @param emailInfo 默认邮件服务器
     */
    private EmailInfo setEmailState(final EmailInfo emailInfo) {
        //根据机构名称查询邮件服务器列表
        List<EmailInfo> emailInfos = queryEmailInfo(emailInfo.getOrganization());
        //判断邮件列表是否为空
        if (emailInfos != null && emailInfos.size() >= 1) {
            //遍历修改机构下其它邮件服务器
            for (EmailInfo ei : emailInfos) {
                ei.setDefaultEmail(false);
                emailRepository.save(ei);
            }
        }
        emailInfo.setDefaultEmail(true);

        handler.doHandler(new LogCallBack() {
            @Override
            public Object doHandler() {
                emailRepository.save(emailInfo);
                return null;
            }

            @Override
            public Log generate() {
                Log log = new Log();
                log.setType("修改");
                log.setName("修改邮件服务器");
                log.setDescription("修改邮件服务器");
                return log;
            }

            @Override
            public boolean forceLog() {
                return false;
            }
        });

        return emailInfo;
    }

    /**
     * 根据机构查询邮件服务器信息
     *
     * @param organization 机构名称
     * @return 邮件服务器列表
     */
    public List<EmailInfo> queryEmailInfo(String organization) {
        List<EmailInfo> emailInfos = emailRepository.queryEmailInfo(organization);
        emailRepository.clear();
        return emailInfos;
    }

    /**
     * 删除邮件服务器信息
     *
     * @param id 邮件服务器id
     */
    public void deleteEmail(final Long id) {
        handler.doHandler(new LogCallBack() {
            @Override
            public Object doHandler() {
                emailRepository.deleteEmail(id);
                return null;
            }

            @Override
            public Log generate() {
                Log log = new Log();
                log.setType("删除");
                log.setName("删除邮件服务器");
                log.setDescription("删除邮件服务器");
                return log;
            }

            @Override
            public boolean forceLog() {
                return false;
            }
        });
    }

    /**
     * 根据机构名称和邮箱号查询邮件服务器信息
     *
     * @param organization 机构
     * @param email        邮箱
     * @return 邮件信息
     */
    public EmailInfo queryEmailInfo(String organization, String email) {
        return emailRepository.queryEmailInfo(organization, email);
    }

    /**
     * 修改邮件服务器信息
     *
     * @param emailInfo 邮件服务器信息
     */
    public EmailInfo updateEmail(final EmailInfo emailInfo) {
        if (emailInfo.isDefaultEmail() || queryEmailInfo(emailInfo.getOrganization()).size() >= 1) {
            return setEmailState(emailInfo);
        }
        handler.doHandler(new LogCallBack() {
            @Override
            public Object doHandler() {
                emailRepository.saveAndFlush(emailInfo);
                return null;
            }

            @Override
            public Log generate() {
                Log log = new Log();
                log.setType("修改");
                log.setName("修改邮件服务器");
                log.setDescription("修改邮件服务器");
                return log;
            }

            @Override
            public boolean forceLog() {
                return false;
            }
        });
        return emailInfo;
    }

}
